//Dispacther provides mods to add their network commands to this dispatcher
// and can be called asap command is arrived from network
// Its a commands dispatcher
// use dispatcher.registerHook to add commands and
// use dispatcher.unregisterHook to delete commands
module.exports = {
    dispatcher: function () {
        this.cmds = {};
        
        this.init = function(){ return true };
        
        //mods callable fn form register hooks
        this.registerHook = function(cmds){
            for ( cmd in cmds) {
                this.cmds[cmd] = cmds[cmd];
            }
        };
        
        this.unregisterHook = function(cmds){
            for ( cmd in cmds) {
                delete(this.cmds[cmd]);
            }
        };
        
        
        //dont call this fn, callee by main
        this.dispatch = function(json){
            if (json != null && json != undefined) {
                for (var key in json){
                    if (key != "" && key != 0 && this.cmds[key] != undefined) {
                        var cmd = this.cmds[key];
                        var mod = this.getMod(cmd['mod']);
                        mod[cmd['fn']](json[key]);
                    }
                }
            }
        };
        
        this.modLoad = function(dir){
            fs.readdir(dir, function(err, files){
                for (i in files) {
                    var filename = files[i];
                    var filenameSplit = filename.split('.');
                    if (filenameSplit[filenameSplit.length - 1] == "js"){
                        var objectName = filename.substr(0, (filename.length - 3));
                        var mod = require("../"+config.mods_dir+filename);
                        main.mods[objectName] = new mod[objectName]();
                        main.mods[objectName].init();
                        console.log('Loaded '+objectName+" !");
                    }
                }
            });
        };
        
        this.modExist = function(modname){
            if (main.mods[modname])
                return true;
            else
                return false;
        };
        
        this.getMod = function(modname){
            if (this.modExist(modname))
                return main.mods[modname];
            else
                return false;
        };
    }
}